package mongo

import (
	"gitee.com/yaodae/server-lib-go/log"
	"gopkg.in/mgo.v2"
	"strings"
	"time"
)

type MgServerConfig struct {
	Name        string
	Hosts       string
	AuthDb      string
	AuthUser    string
	AuthPass    string
	MaxPoolSize int
}

var pools map[string]*mgo.Session
var DefaultDb string

func getConn(db string) *mgo.Session {
	pool, ok := pools[db]
	if ok {
		return pool.Copy()
	} else {
		return pools[DefaultDb].Copy()
	}
}

func releaseConn(s *mgo.Session) {
	s.Close()
}

func initMongo(config MgServerConfig) {
	pools = make(map[string]*mgo.Session)
	pool := initDb(config)
	if pool != nil {
		pools[config.Name] = pool
		DefaultDb = config.Name
	}
}

func initDb(config MgServerConfig) *mgo.Session {
	log.Info("mongo hosts=" + config.Hosts)
	mongoDBDialInfo := &mgo.DialInfo{
		Addrs:    strings.Split(config.Hosts, ","),
		Timeout:  60 * time.Second,
		Database: config.AuthDb,
		Username: config.AuthUser,
		Password: config.AuthPass,
	}
	session, err := mgo.DialWithInfo(mongoDBDialInfo)
	if err != nil {
		panic(`mongo initDb: data(` + config.Hosts + `): ` + err.Error())
	}
	session.SetPoolLimit(config.MaxPoolSize)
	session.SetMode(mgo.Monotonic, true)
	return session
}

func closeDb() {
	session, ok := pools[DefaultDb]
	if ok {
		session.Close()
	}
}
